<?php

Cookie::Read();

//Events::On('headers', 'beforeflush', 'Cookie::WriteAll');

class Cookie {

	protected static $_cookies = array();
	protected static $_changed = array();

	public static function Get($name) {
		if (isset(self::$_cookies[$name])) {
			
		}
	}

	public static function Set($name, $value) {
		if (isset(self::$_cookies[$name])) {
			return new Cookie($name, $value);
		}
	}

	public static function Purge() {
		foreach (self::$_cookies as $key => $val) {
			$val->Delete();
		}
	}

	public static function Read($prefix = null, $values = null) {
		if (is_null($values)) {
			$values = $_COOKIE;
		}

		foreach ($values as $key => $val) {
			$name = !is_null($prefix) ? $key : "{$prefix}[$key]";
			if (!is_array($val)) {
				self::$_cookies[$name] = new Cookie($name, $val);
			} else {
				self::Read($name, $val);
			}
		}
	}

	public static function WriteAll() {
		foreach ($this->_changed as $name => $val) {
			$this->_cookies[$name]->Write();
		}
	}

	public function __construct($name, $value) {
		$this->_name = $name;
		$this->_value = $value;
		$this->_attrs = array();
	}

	public function GetName() {
		return $this->_name;
	}

	public function GetValue() {
		return $this->_value;
	}

	public function SetValue($value) {
		self::$_changed[$this->_name] = true;
		$this->_value = $value;
		return $this;
	}

	public function SetExpire($value) {
		self::$_changed[$this->_name] = true;
		$this->_attrs['expire'] = self::ParseExpire($value);
		return $this;
	}

	public function SetPath($value) {
		self::$_changed[$this->_name] = true;
		$this->_attrs['path'] = $value;
		return $this;
	}

	public function SetDomain($value) {
		self::$_changed[$this->_name] = true;
		$this->_attrs['domain'] = $value;
		return $this;
	}

	public function SetSecure($value) {
		self::$_changed[$this->_name] = true;
		$this->_attrs['secure'] = $value;
		return $this;
	}

	public function SetHTTPOnly($value) {
		self::$_changed[$this->_name] = true;
		$this->_attrs['httponly'] = !!$value;
		return $this;
	}

	public function Delete() {
		self::$_changed[$this->_name] = true;
		$this->_attrs = array(
			'expire' => time() - 86400
		);
	}

	public function Write() {
		global $config;

		$_default_attrs = array(
			'expire' => 0,
			'path' => $config['relpath'],
			'domain' => $config['domain'],
			'secure' => false,
			'httponly' => false
		);

		$attrs = array_merge(
			self::$_default_attrs,
			$this->_attrs
		);

		$args = array(
			$this->_name,
			$this->_value,
			$attrs['expire'],
			$attrs['path'],
			$attrs['domain'],
			$attrs['secure'],
			$attrs['httponly']
		);

		call_user_func_array('setcookie', $args);
	}

}
